package org.darcy.config.shiro;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * 缓存服务
 */
@Service
@Slf4j
public class EhcacheService {

	private final String cacheName = "mycache";

	@Autowired
	private CacheManager CacheManager;

	@Cacheable(value = cacheName, key = "#key")
	public String getData(String key) {
		log.info("从缓存获取数据...");
		return key + ":" + String.valueOf(Math.round(Math.random() * 1000000));
	}

	@CacheEvict(value = cacheName, key = "#key")
	public void removeData(String key) {
		log.info("从缓存删除数据");
	}

	@CachePut(value = cacheName, key = "#key")
	public String refreshData(String key) {
		log.info("模拟从数据库中加载数据");
		return key + "::" + String.valueOf(Math.round(Math.random() * 1000000));
	}

	@CacheEvict(value = "UserCache", allEntries = true)
	public void removeAll() {
		log.info("清除掉UserCache中全部的缓存");
	}

	/**
	 * 判断key是否存在
	 */
	public boolean hasKey(String key) {
		Cache cache = CacheManager.getCache(cacheName);
		Element value = cache.get(key);
		if (value == null) {
			return false;
		}
		return true;
	}

	/**
	 * 设置值
	 */
	public void set(String key, String value) {
		Cache cache = CacheManager.getCache(cacheName);
		Element e = new Element(key, value);
		cache.put(e);
	}

	/**
	 * 登录次数加1
	 */
	public void increment(String key) {
		Cache cache = CacheManager.getCache(cacheName);
		Element value = cache.get(key);
		if (value == null) {
			value = new Element(key, 0);
		}
		int count = (int) value.getObjectValue();
		value = new Element(key, count + 1);
		cache.put(value);
		log.info("用户【{}】登录次数: {}", key, value.getObjectValue());
	}

	/**
	 * 获取用户登录次数
	 */
	public int getLoginCount(String key) {
		Cache cache = CacheManager.getCache(cacheName);
		Element value = cache.get(key);
		if (value == null) {
			value = new Element(key, 0);
		}
		int count = (int) value.getObjectValue();
		return count;
	}

	/**
	 * 清空登录计数
	 */
	public void delete(String key) {
		Cache cache = CacheManager.getCache(cacheName);
		Element value = new Element(key, 0);
		cache.put(value);
	}

}